package com.stormragetech.teamwork.common.util;

import com.stormragetech.common.exception.StormragetechException;
import com.stormragetech.teamwork.common.constant.Constants;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
public class AESCrypt {

    private static final Integer ENCRYPT_CODE = 0; // 加密
    private static final Integer DECRYPT_CODE = 1; // 解密

    public static String encrypt(String data, String key) throws StormragetechException {

        try {
            byte[] source = data.getBytes(Constants.ENCODING);
            return byteToHexStr(encrypt(source, key));
        } catch (Exception e) {
            throw new StormragetechException(Constants.CRYPT_ERR_CODE, e.getMessage(), e);
        }

    }

    public static String decrypt(String data, String key) throws StormragetechException {

        try {
            byte[] source = hexStrToByte(data);
            return new String(decrypt(source, key), Constants.ENCODING);
        } catch (Exception e) {
            throw new StormragetechException(Constants.CRYPT_ERR_CODE, e.getMessage(), e);
        }

    }

    private static byte[] encrypt(byte[] data, String key) throws Exception {

        Cipher cipher = initCipher(ENCRYPT_CODE, key);
        return cipher.doFinal(data);

    }

    private static byte[] decrypt(byte[] data, String key) throws Exception {

        Cipher cipher = initCipher(DECRYPT_CODE, key);
        return cipher.doFinal(data);

    }

    private static Cipher initCipher(Integer handleCode, String key) throws Exception {

        SecretKeySpec keySpec = generateKey(key);
        Cipher cipher = Cipher.getInstance(Constants.AES_ALGORITHM);
        if (ENCRYPT_CODE.equals(handleCode)) {
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
        }

        return cipher;

    }

    private static SecretKeySpec generateKey(String key) throws Exception {

        KeyGenerator keyGen = KeyGenerator.getInstance(Constants.AES_ALGORITHM);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes());
        keyGen.init(Constants.AES_BIT, random);
        SecretKey secretKey = keyGen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();

        return new SecretKeySpec(enCodeFormat, Constants.AES_ALGORITHM);

    }

    private static String byteToHexStr(byte[] source) {

        if (null == source) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        for (byte sour : source) {
            String hex = Integer.toHexString(sour & 0xFF);
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();

    }

    private static byte[] hexStrToByte(String source) {

        if (null == source || source.isEmpty()) {
            return null;
        }

        byte[] result = new byte[source.length() / 2];
        for (int i = 0; i < source.length() / 2; i++) {
            int high = Integer.parseInt(source.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(source.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }

        return result;

    }

}
